/*
 * @Description: 创建广告
 * @Author: kanglin
 * @Date: 2018-06-20 10:05:57
 * @Copyright: Created by Panxsoft.
 */

<style lang="less" scoped rel="stylesheet/less" type="text/less" >
    .advert-create{
			height: 78vh;
			overflow-y: scroll;

      .device__account{
        max-width: 450px;
      }

      .redirect_img_thumb {
        height: 50px;
        vertical-align: middle;
      }
		}
		  .v-component-bosupload {
        position: relative;
        display: inline-block;
        background: #fff;
        border: 1px solid #dddee1;
        border-radius: 4px;
        padding: 6px 23px;
        overflow: hidden;
        color: #495060;
        text-decoration: none;
        text-indent: 0;
		line-height: 20px;
		max-width: 288px;
		white-space: nowrap;
		text-overflow: ellipsis;
        input[type='file'] {
            position: absolute;
            font-size: 100px;
            right: 0;
            top: 0;
			opacity: 0;
			max-width: 300px;
        }
        &:hover {
            // background: #AADFFD;
            border-color: #57a3f3;
            color: #57a3f3;
            text-decoration: none;
        }
    }
</style>

<template>
	<div class="advert-create">
		<Row
			type="flex"
			justify="start">
			<i-col push="1">
				<Form
					ref="formValidate"
					:model="formValidate"
					:rules="ruleValidate"
					:label-width="labelWidth(110, 150)"
					name="create__form"
					class="device__account">
					<FormItem
						:label="$t('advert.name')"
						prop="name">
						<i-input
							v-model="formValidate.name"
							:placeholder="$t('advert.please_enter_name')"
							name="create__name"/>
					</FormItem>

					<Form-item
						:label="$t('advert.media_type')"
						prop="advert_type_id">

						<Select
							v-model="formValidate.advert_type_id"
							clearable
							filterable
							style="width:200px"
							name="create-advert"
						>
							<Option
								v-for="item in advert_types"
								:value="item.id"
								:key="'advert_type' + item.id">{{ item.name }}
							</Option>
						</Select>

					</Form-item>

					<!-- 多语言 -->
					<Tabs

						v-model="language_id"

					>
						<TabPane
							v-for="(locale_suggest, locale_idx) in language_index"
							:key="`hm_tab_lang[${locale_idx}]`"
							:label="locale_suggest.name"

						>


							<!-- 中文.视频图片-->
							<Form-item
								v-if="formValidate.advert_type_id"
								v-show="locale_idx==1?false:true"
								:label="$t('advert.advert_img_video')"
								prop="instruction_zh_img"
							>

								<a
									href="javascript:;"
									class="v-component-bosupload">
									{{ file_info || $t('bosupload.selector') }}
									<input
										ref="bos_btn"
										:accept="accept"
										:multiple="multiple"
										:name="name"
										:tips="$t('advert.select_file')"
										:file-type-reg-exp="fileTypeRegExp"
										type="file"

										@change="changeInput">

								</a>
								<p>{{ uploadTips }}</p>
							</Form-item>

							<!-- 英文视频图片-->
							<Form-item
								v-if="formValidate.advert_type_id"
								v-show="locale_idx==1?true:false"
								:label="$t('advert.advert_img_video')"
								prop="instruction_en_img"
							>

								<a
									href="javascript:;"
									class="v-component-bosupload">
									{{ file_info_en || $t('bosupload.selector') }}
									<input
										ref="bos_btn"
										:accept="accept"
										:multiple="multiple"
										:name="name"
										type="file"

										@change="changeInput_en">
								</a>
								<p>{{ uploadTips_en }}</p>
							</Form-item>


							<!-- 中文跳转类型 -->
							<Form-item
								v-show="locale_idx==1?false:true"
								:label="$t('advert.redirect_type')"
								prop="redirect_zh_type">

								<Select
									v-model="formValidate.redirectable_zh_type"
									:placeholder="$t('common.none')"
									clearable
									name="create__redirectable_zh_type"

								>
									<Option
										v-for="redirect_type in redirect_types"
										:value="redirect_type.id"
										:key="'redirect_type' + redirect_type.id">{{ redirect_type.name }}
									</Option>
								</Select>
							</Form-item>

							<!-- 中文跳转网址 -->
							<Form-item

								v-show="locale_idx==1?false:true"
								:label="$t('advert.redirect_url')"
								required
								prop="redirect_zh_url">

								<i-input
									v-model="formValidate.redirect_zh_url"
									:placeholder="$t('advert.please_enter_url')"
									name="create_redirect_zh_url"/>
							</Form-item>

							<!-- 英文跳转类型 -->
							<Form-item
								v-show="locale_idx==1?true:false"
								:label="$t('advert.redirect_type')"
								prop="redirect_en_type">

								<Select
									v-model="formValidate.redirectable_en_type"
									:placeholder="$t('common.none')"
									clearable
									name="create_redirectable_en_type"

								>
									<Option
										v-for="redirect_type in redirect_types"
										:value="redirect_type.id"
										:key="'redirect_type' + redirect_type.id">{{ redirect_type.name }}
									</Option>
								</Select>
							</Form-item>

							<!-- 英文跳转网址 -->
							<Form-item

								v-show="locale_idx==1?true:false"
								:label="$t('advert.redirect_url')"
								required
								prop="redirect_en_url">

								<i-input
									v-model="formValidate.redirect_en_url"
									:placeholder="$t('advert.please_enter_url')"
									name="create__redirect_en_url"/>
							</Form-item>
						</TabPane>
					</tabs>


					<Form-item
						v-if="formValidate.advert_type_id!==2"
						:label="$t('advert.play_second')"
						prop="play_second">
						<InputNumber

							v-model="formValidate.play_second"
							:placeholder="$t('advert.please_enter_play_second')"
							readonly
							name="create__play_second"/>
					</Form-item>

					<!-- 是否跳过广告 -->
					<Form-item
						v-if="formValidate.advert_type_id==1"
						:label="$t('advert.ispass_advert')"
					>
						<RadioGroup
							v-model="formValidate.radio"

						>
							<Radio label="true">是</Radio>
							<Radio label="false">否</Radio>
						</RadioGroup>

					</Form-item>

					<!-- 排序 -->
					<Form-item
						:label="$t('announcement.sort_order')"
						prop="sort_order">
						<InputNumber
							:min="1"

							v-model="formValidate.sort_order"
							:placeholder="$t('announcement.please_select_sort_order')"
							name="create-sort"/>
					</Form-item>


					<!-- 开始时间 -->

					<Form-item
						:label="$t('announcement.started_at')"
						prop="started_at">
						<DatePicker
							v-model="formValidate.started_at"
							:style="{width: '260px'}"
							:placeholder="$t('announcement.please_select_started_at')"
							type="datetime"
							placement="top"
							name="create-started_at"
							@on-change="changeSTDate"/>
					</Form-item>

					<!-- 结束时间 -->
					<Form-item
						:label="$t('announcement.ended_at')"
						prop="ended_at">
						<DatePicker
							v-model="formValidate.ended_at"
							:style="{width: '260px'}"
							:placeholder="$t('announcement.please_select_ended_at')"
							type="datetime"
							placement="top"
							name="create-ended_at"
							@on-change="changeEDDate"/>
					</Form-item>


					<Form-item>
						<Button
							type="primary"
							name="create__submit"
							@click="handleSubmit('formValidate')">{{ $t('common.submit') }}</Button>
						<Button
							type="ghost"

							style="margin-left: 8px"
							@click="handleReset('formValidate')">{{ $t('common.reset') }}</Button>
					</Form-item>
				</Form>
			</i-col>
		</Row>
	</div>
</template>


<script>
import API_LIST from 'src/API_LIST';
import labelWidthMixin from 'src/views/mixins/labelWidthMixin';
import { mapMutations } from 'vuex';
import { validateFile } from 'src/validate';
import { isUrlValidate } from 'src/utils/utils';
import Uploader from 'src/views/component/uploader';
import { $t } from 'src/i18n';

const [ADVERT_TYPE_ID_IMAGE, ADVERT_TYPE_ID_VIDEO, ADVERT_TYPE_ID_TABLE_PLAQUE] = [1, 2, 3]; // 常量
const [REDIRECTABLE_TYPE_URL] = ['Url'];

export default {
	name: 'AdvertCreate',
	components: {
		Uploader,
	},
	mixins: [labelWidthMixin],
	props: {
		// oss_sign: {
		// 	type: Object,
		// 	required: true,
		// },
		language_index: {
			type: Array,
			default() {
				return [];
			},
		},
		advert_types: {
			type: Array,
			default() {
				return [];
			},
		},
		// accept: {
		// 	type: String,
		// 	default() {
		// 		return 'video/mp4';
		// 	},
		// },
		multiple: {
			type: Boolean,
			default() {
				return false;
			},
		},
		name: {
			type: String,
			default() {
				return '';
			},
		},

	},
	data() {
		return {

			file_info: '',

			file_info_en: '',

			is_show: 1, // 1表示跳过
			real_started_at: '', // 格式化后的开始时间
			language_id: 0,


			 real_ended_at: '', // 格式化后的结束时间

			formValidate: {
				advert_type_id: '', // 广告类别id 1 图片 2 视频
				name: null, // 广告名称
				content_key: null, // 广告内容 bos的key值 ，create方法获取bos 配置
				play_second: 5, // 播放时长
				device_account_ids: [], // 设备id，create 方法获取
				redirectable_zh_type: '', // 跳转类型
				redirectable_en_type: '', // 跳转类型
				// redirectable_id: 0, // 跳转整妆ID
				redirect_zh_url: '', // 跳转网址的地址
				redirect_en_url: '', // 跳转网址的地址

				sort_order: 1, // 排序

				started_at: '', // 开始时间

				ended_at: '', // 结束时间

				radio: 'true',

				instruction_zh_img: '',

				instruction_en_img: '',
			}, // 新增表单数据
			ruleValidate: { // 表单验证规则
				name: [
					{
						required: true,
						message: this.$t('validate.required', { field: this.$t('advert.name') }),
						trigger: 'blur',
					},
				],
				play_second: [
					{
						required: true,
						type: 'number',
						message: this.$t('validate.required', { field: this.$t('advert.play_second') }),
						trigger: 'blur',
					},
				],

				sort_order: [
					{
						required: true,
						type: 'number',
						message: this.$t('validate.required', { field: this.$t('announcement.sort_order') }),
						trigger: 'blur,change',
					},
				],
				started_at: [
					{
						required: true,
						type: 'date',
						message: this.$t('validate.required', { field: this.$t('announcement.started_at') }),
						trigger: 'blur,change',
					},
				],
				ended_at: [
					{
						required: true,
						type: 'date',
						message: this.$t('validate.required', { field: this.$t('announcement.ended_at') }),
						trigger: 'blur,change',
					},
				],
				redirect_zh_url: [{
					trigger: 'blur,change',
					validator: this.validateRedirectUrl.bind(this),
				}],
				redirect_en_url: [{
					trigger: 'blur,change',
					validator: this.validateRedirectUrl_en.bind(this),
				}],
      	advert_type_id: [
					{
						required: true,
						type: 'number',
						message: this.$t('validate.required', { field: this.$t('advert.media_type') }),
						trigger: 'blur,change',
					},
				],
				// instruction_zh_img: [
				// 	{ required: true, validator: validateFile, trigger: 'blur,change' },
				// ],
				// instruction_en_img: [
				// 	{ required: true, validator: validateFile, trigger: 'blur,change' },
				// ],
			},
			image: ADVERT_TYPE_ID_IMAGE, // 指定当前选项的 value 值
			video: ADVERT_TYPE_ID_VIDEO, // 指定当前选项的 value 值
			accepts: { // 设置 bos accept
				[ADVERT_TYPE_ID_IMAGE]: 'image/gif, image/jpeg, image/png',
				[ADVERT_TYPE_ID_VIDEO]: 'video/mp4',
			},
			   [ADVERT_TYPE_ID_TABLE_PLAQUE]: 'image/gif, image/jpeg, image/png',
			regExps: { // 设置 校验文件类型的正则
				[ADVERT_TYPE_ID_IMAGE]: /(image\/gif|image\/jpeg|image\/png)/i,
				[ADVERT_TYPE_ID_VIDEO]: /video\/MP4/i,
				[ADVERT_TYPE_ID_TABLE_PLAQUE]: /(image\/gif|image\/jpeg|image\/png)/i,
			},
			tips: { // 提示
				[ADVERT_TYPE_ID_VIDEO]: this.$t('advert.video_format'),
				[ADVERT_TYPE_ID_IMAGE]: this.$t('advert.image_format'),
				[ADVERT_TYPE_ID_TABLE_PLAQUE]: this.$t('advert.image_format'),
			},

			TYPE_IMAGE: ADVERT_TYPE_ID_IMAGE,
			TYPE_VIDEO: ADVERT_TYPE_ID_VIDEO,
			TYPE_TABLE_PLAQUE: ADVERT_TYPE_ID_TABLE_PLAQUE,
			// REDIRECTABLE_TYPE_PACK,
			// REDIRECTABLE_TYPE_PRODUCT,
			REDIRECTABLE_TYPE_URL,

			redirect_types: [
				// { name: this.$t('advert.redirect_pack'), id: REDIRECTABLE_TYPE_PACK },
				// { name: this.$t('advert.redirect_product'), id: REDIRECTABLE_TYPE_PRODUCT },
				{ name: this.$t('advert.redirect_url'), id: REDIRECTABLE_TYPE_URL },
			],
		};
	},
	computed: {
		accept() {
			const key = this.formValidate.advert_type_id;
			return this.accepts[key];
		},
		fileTypeRegExp() {
			const key = this.formValidate.advert_type_id;
			return this.regExps[key];
		},
		uploadTips() {
			const key = this.formValidate.advert_type_id;
			return this.tips[key];
		},

		uploadTips_en() {
			const key = this.formValidate.advert_type_id;
			return this.tips[key];
		},
	},

	watch: {
		// 'formValidate.advert_type_id': {
		// 	handler() {
		// 		this.removeFile();
		// 	},
		// },
	},

	methods: {
		...mapMutations('spinShow', [
			'showSpin',
			'closeSpin',
		]),

		changeSTDate(date) {
			this.real_started_at = date;
		},

		changeEDDate(date) {
			this.real_ended_at = date;
		},

		// 切换英文tabs
		change_en_language() {
			if (event.keyCode == 9) {
							 this.language_id = 1;
				 }
		},
		// 切换中文tabs
		change_zh_language() {
      	if (event.keyCode == 9) {
							 this.language_id = 0;
				 }
		},


		/**
		 * 重置 bos upload 组件
		 * @return {undefined}
		 */
		removeFile() {
			if (this.$refs.bos_btn) {
				const $bos_btn = this.$refs.bos_btn;
				$bos_btn.value = '';
			}
			this.file_info = '';
			this.file_info_en = '';
		},


		/**
		 * 表单提交
		 * @param {String} name {表单上的ref值}
 		 */
		handleSubmit(name) {
			this.$refs[name].validate((valid) => {
				if (valid) {
					if (this.formValidate.instruction_zh_img == '') {
						this.$Message.error(this.$t('advert.file_cannot_be_empty_zh'));
						return;
					}
					if (this.formValidate.instruction_en_img == '') {
						this.$Message.error(this.$t('advert.file_cannot_be_empty_en'));
						return;
					}
           	this.formDataCreate();
				} else {
					this.$Message.error(this.$t('common.invalid_form_data'));
				}
			});
		},

		/**
         * 手动拼接表单数据
		 * @param {new_object} {拼接表单对象}
         * @return {undefined}
         */
		formDataCreate() {
			if (this.formValidate.radio == 'false') {
			   this.is_show = 0;
			 }


			const new_array = [
				{
					id: 1,
					content: this.formValidate.instruction_zh_img,
				},
				{
					id: 3,
					content: this.formValidate.instruction_en_img,
				},
			];


			 if (this.formValidate.redirectable_zh_type && this.formValidate.redirectable_en_type) {
				 new_array[0].redirectable_type = this.formValidate.redirectable_zh_type;
				 new_array[1].redirectable_type = this.formValidate.redirectable_en_type;

				  new_array[0].redirect_url = this.formValidate.redirect_zh_url;
				 new_array[1].redirect_url = this.formValidate.redirect_en_url;
			 }

			const new_object = {

				name: this.formValidate.name,

				advert_type_id: this.formValidate.advert_type_id,

				sort_order: this.formValidate.sort_order,

				started_at: this.real_started_at,

				ended_at: this.real_ended_at,

				can_skip: this.is_show,
			};

			// if (this.formValidate.advert_type_id == 1) {
			// 			 new_object.can_skip = this.is_show;
			// }
			if (this.formValidate.advert_type_id !== 2) {
				   new_object.play_second = this.formValidate.play_second;
			}

			const form_data = new FormData();

			Object.keys(new_object).forEach((key) => {
				form_data.append(key, new_object[key]);
			});

     			// dexcriptions需为数组
			for (let i = 0; i < new_array.length; i++) {
				for (const key in new_array[i]) {
					form_data.append(`descriptions[${new_array[i].id}][${key}]`, new_array[i][key]);
				}
			}


			this.$emit('postStore', form_data);
		},
		/**
		 * 表单重置
		 * @param  {String} name {表单上的ref的值}
		 * @return {undefined}
		 */
		handleReset(name) {
			this.removeFile();

			this.$refs[name].resetFields();
			this.formValidate.play_second = 5;

			this.formValidate.radio = 'true';

			this.formValidate.redirectable_zh_type = '';

			this.formValidate.redirectable_en_type = '';
		},


		/**
     * @return {boolean}
     */
		// packSelectionVisible() {
		// 	return this.formValidate.redirectable_type === REDIRECTABLE_TYPE_PACK
		//     && this.isAdvertTypeImage();
		// },
		/**
     * @return {boolean}
     */
		// assetSelectionVisible() {
		// 	return this.formValidate.redirectable_type === REDIRECTABLE_TYPE_PRODUCT
		//     && this.isAdvertTypeImage();
		// },
		/**
     * @return {boolean}
     */
		// urlInputVisible() {
		// 	return this.formValidate.redirectable_zh_type === REDIRECTABLE_TYPE_URL;
		// },

		// urlInputVisible_en() {
		// 	return this.formValidate.redirectable_en_type === REDIRECTABLE_TYPE_URL;
		// },


		validateRedirectUrl(rule, value, callback) {
			const isRedirectTypeUrl = this.formValidate.redirectable_zh_type === this.REDIRECTABLE_TYPE_URL;

			if (isRedirectTypeUrl && !isUrlValidate(value)) {
				callback(this.$t('validate.url', { field: this.$t('advert.redirect_url') }));
			} else {
				callback();
			}
		},

    		validateRedirectUrl_en(rule, value, callback) {
			const isRedirectTypeUrl = this.formValidate.redirectable_en_type === this.REDIRECTABLE_TYPE_URL;

			if (isRedirectTypeUrl && !isUrlValidate(value)) {
				callback(this.$t('validate.url', { field: this.$t('advert.redirect_url') }));
			} else {
				callback();
			}
		},


		changeInput(e) {
			this.formValidate.instruction_zh_img = e.target.files[0];
			if (this.validateFileType(e.target.files[0])) {
				this.file_info = e.target.files[0].name;
			} else {
				this.file_info = '';
			}
		},

		changeInput_en(e) {
			this.formValidate.instruction_en_img = e.target.files[0];
			if (this.validateFileType(e.target.files[0])) {
				this.file_info_en = e.target.files[0].name;
			} else {
				this.file_info_en = '';
			}
		},


		/**
         * 校验文件类型
         * @param  {Object} file {文件对象}
         * @return {Boolean} {true代表校验通过，false代表不通过}
         */
		validateFileType(file) {
			if (!file) {
				this.$Message.error(this.$t('bosupload.no_files_selected')); // 未选择任何文件！
				return;
			}

			const file_type = file.type;

			if (this.fileTypeRegExp.test(file_type)) {
				if (parseFloat(file.size) / 1024 > 102400) {
					this.$Message.error(this.$t('bosupload.size_max', { value: '100m' })); // '所选文件超过100M限制！'

					this.$emit('validate', false);

					return false;
				}

				this.$emit('validate', true);

				return true;
			}

			this.$Message.error(this.$t('bosupload.format_error')); // 所选文件格式不正确！

			this.$emit('validate', false);

			return false;
		},

	},
};
</script>
